package com.g2room.myuall.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;

import com.g2room.myuall.grap.univ.GenericGrap;
import com.g2room.myuall.util.StringUtil;

public class ImageUtil {
	public static String path = "D:/userdata/imags/univ/";

	public static void main(String[] args) {
	}
	/**
	 * 保存图片到ky文件夹
	 * @param urlStr
	 * @return	保存的文件名称
	 * @throws Exception
	 */
	public static String downloadImage2Ky(String url, String folder, int id) throws Exception {
		return downloadImage(url, path, folder, id+".jpg");
	}
	public static String downloadImage2Ky(String url, String folder) throws Exception {
		return downloadImage(url, path, folder, "");
	}
	/**
	 * 保存图片到指定文件夹
	 * @param urlStr
	 * @return	保存的文件名称
	 * @throws Exception
	 */
	public static String downloadImageByType(String urlStr, String type) throws Exception {
		return downloadImage(urlStr, path, "ky", type);
	}
	/**
	 * 保存图片到指定文件夹
	 * @param urlStr
	 * @return	保存的文件名称
	 * @throws Exception
	 */
	public static String downloadImage(String urlStr, String path) throws Exception {
		return downloadImage(urlStr, path, path, null);
	}
	
	/**
	 * 
	 * @param urlStr
	 * @param folder	存放目录：E:/高绪国/资料/html/qgsh/images/
	 * @param path	相对目录，建议为每个抓取文章类型
	 * @param type	图片默认类型，为空则取连接后面的图片类型
	 * @return
	 * @throws Exception
	 */
	public static String downloadImage(String urlStr, String folder, String dir, String fileName) throws Exception {
//		String fileName = urlStr;
		if(null == fileName || fileName.length() ==0) {
//			if(urlStr.contains(".")) {
//				fileName = urlStr.substring(urlStr.lastIndexOf("/"));
//			} else {
				fileName = urlStr.substring(urlStr.lastIndexOf("/")) + ".jpg";
//			}
		}
//		fileName = System.nanoTime() + genRandomCode(6) + fileName;
	    // 构造URL
	    URL url = new URL(urlStr);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", GenericGrap.uas[new Random().nextInt(GenericGrap.uas.length -1)]);
	    
	    // 打开连接
//	    URLConnection con = url.openConnection();
	    InputStream is = con.getInputStream();
	    if(is.available() <= 1100) return null;
//	    System.out.println(is.available());
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
//	    File file = new File(folder);
//	    if(!file.exists()) file.mkdirs();
	    String filePath = folder + dir +  fileName;
	    File file1 = new File(filePath);
	    // 判断文件是否存在
	    if(file1.exists()) {
	    	return filePath;
	    }
	    // 输出的文件流
	    OutputStream os = new FileOutputStream(file1);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	    return filePath;
	}
	
	/**
	 * 获取指定位数的随机数字
	 * 
	 * @param len  指定长度
	 * @return
	 * @auther <a href="mailto:gaoxuguo@stargame.com">高绪国</a>
	 */
	public static String genRandomCode(int len) {
		// 35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 62;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
				'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
				'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
				'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		StringBuffer randomNum = new StringBuffer("");
		Random r = new Random();
		while (count < len) {
			// 生成随机数，取绝对值，防止生成负数，
			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
			if (i >= 0 && i < str.length) {
				randomNum.append(str[i]);
				count++;
			}
		}
		return randomNum.toString();
	}
	public static Map<Integer, Integer> getImgWidth(String url) {
		Map<Integer, Integer> widthAndHeight = null;
		if(StringUtil.isEmpty(url)) return widthAndHeight;
		try {
			URL u = new URL(url);
			URLConnection urlconn = u.openConnection();
			urlconn.setConnectTimeout(5000);// 设置连接时间
			urlconn.setReadTimeout(5000);// 设置超时时间
			urlconn.setRequestProperty("User-Agent",GenericGrap.uas[new Random().nextInt(GenericGrap.uas.length -1)]);
	    	BufferedImage sourceImg =ImageIO.read(urlconn.getInputStream());
	    	
	    	if(null != sourceImg) {
	    		widthAndHeight = new HashMap<Integer, Integer>();
	    		widthAndHeight.put(sourceImg.getWidth(), sourceImg.getHeight());
	    	}
	    } catch (Exception e) {
	    	System.out.println("获取图片错误：" + url);
	    }
		return widthAndHeight;
	}
}
